﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

using EzDesk.Generic;

namespace EzDesk.Generic.Collections
{
    public class RangeCollection<T> : ObservableCollection<T>
    {
        private int _maxCount = int.MaxValue;
        private bool releaseItem = true;


        public RangeCollection()
        {
        }

        public RangeCollection(int maxCount)
        {
            this.ResetMaxCount(maxCount);
        }

        public void ResetMaxCount(int maxCount)
        {
            this._maxCount = maxCount;
        }

        public RangeCollection(int maxCount, ObservableCollection<T> source)
        {
            this._maxCount = maxCount;
            int max = Math.Min(_maxCount, source.Count);
            for (int i = 0; i < max; i++)
            {
                this.InsertItem(i, source[i]);
            }
        }

        public RangeCollection<T> InsertItemAtFirst(T item)
        {
            this.InsertItem(0, item);
            this.Cut();
            return this;
        }

        protected override void OnCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            base.OnCollectionChanged(e);
            this.Cut();
        }

        private void Cut()
        {
            while (this.Count > _maxCount)
            {
                int index = this.Count - 1;
                if (releaseItem)
                {
                    var item = this[index] as IDisposable;
                    if (item !=null)
                    {
                        item.Dispose();
                    }
                }
                this.RemoveAt(index);
            }
        }
    }
}
